﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

using MyUtils;

using SolutionOrchestrator.Validators;

namespace SolutionOrchestrator
{
	public class DataCtx : ObservableObject
	{
		readonly IProgress _progress;
		readonly IMySettingsProvider _settings;
		readonly IRuleSet _rules;
		readonly ObservableCollection<Violation> _violations = new ObservableCollection<Violation>();

		public ObservableCollection<Violation> Violations { get { return _violations; } }
		public IEnumerable<string> RootPathCollection { get { return _settings.RootPathCollection; } }

		public MySettings Settings
		{
			get { return _settings.Get; }
		}

		public IProgress Progress
		{
			get { return _progress; }
		}

		public DataCtx(IProgress progress, IMySettingsProvider settings, IRuleSet rules)
		{
			_progress = progress;
			_settings = settings;
			_rules = rules;
			_violations.CollectionChanged += ViolationsCollectionChanged;
		}

		void ViolationsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			var handler = _requeryFixAll.Value;
			if (handler != null)
			{
				handler(null, null);
			}
		}

		public object Rules
		{
			get { return _rules.All.ToList(); }
		}

		string _sourceControlError;

		public string SourceControlError
		{
			get { return _sourceControlError; }
			set
			{
				_sourceControlError = value;
				OnPropertyChanged("SourceControlError");
			}
		}

		bool _showSourceControlSettings;

		public bool ShowSourceControlSettings
		{
			get { return _showSourceControlSettings; }
			set
			{
				_showSourceControlSettings = value;
				OnPropertyChanged("ShowSourceControlSettings");
			}
		}

		string _sourceControlErrorFile;
		public string SourceControlErrorFile
		{
			get { return _sourceControlErrorFile; }
			set
			{
				_sourceControlErrorFile = value;
				OnPropertyChanged("SourceControlErrorFile");
				OnPropertyChanged("SourceControlErrorRelativeFile");
			}
		}

		public string SourceControlErrorRelativeFile
		{
			get { return _sourceControlErrorFile == null ? null : PathHelper.BuildRelativeFromTo(_settings.CurrentRootPath, _sourceControlErrorFile) ?? _sourceControlErrorFile; }
		}

		readonly Box<EventHandler> _requeryFixAll = new Box<EventHandler>();

		public ICommand FixAll
		{
			get
			{
				return new DelegateCommand(delegate
				{
					foreach (var violation in Violations.OfType<FixableViolation>())
					{
						if (violation.DefaultExists)
						{
							violation.ApplyFix(violation.DefaultFix);
						}
					}
				}, () => Violations.OfType<FixableViolation>().Any(x => x.DefaultExists), _requeryFixAll, false);
			}
		}

	}
}
